package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.Contract;
import cn.itcast.domain.cargo.ContractExample;
import cn.itcast.domain.system.User;
import cn.itcast.service.cargo.ContractService;
import cn.itcast.service.system.UserService;
import cn.itcast.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/cargo/contract")
@Slf4j
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;

    @Autowired
    private UserService userService;




    /**
     * 1. 列表
     */
    @RequestMapping("/list")
    public String list(@RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行购销合同列表查询开始...");
        // 构造条件对象
        ContractExample contractExample = new ContractExample();
        // 根据create_time降序排序
        contractExample.setOrderByClause("create_time desc");
        // 获取条件的集合
        ContractExample.Criteria criteria = contractExample.createCriteria();
        // 添加条件
        criteria.andCompanyIdEqualTo(getLoginCompanyId());
        /**
         * 登陆用户的degree
         *   2-管理所有下属部门和人员
         *   3-管理本部门
         *   4-普通员工
         */
        User loginUser = getLoginUser();
        Integer degree = loginUser.getDegree();
        PageInfo<Contract> pageInfo = null;
        // 判断用户的等级
        if (degree == 4) {
            //A.登陆用户的degree=4,说明是普通用户，只能查看自己创建的购销合同
            //SELECT * FROM co_contract WHERE create_by='登陆用户的id'
            criteria.andCreateByEqualTo(loginUser.getId());
            pageInfo = contractService.findByPage(contractExample, pageNum, pageSize);
        }
        else if (degree == 3) {
            //B.登陆用户的degree=3,说明是部门经理，可以查看本部门下的所有购销合同
            //SELECT * FROM co_contract WHERE create_dept='登陆用户的部门id'
            criteria.andCreateDeptEqualTo(loginUser.getDeptId());
            pageInfo = contractService.findByPage(contractExample, pageNum, pageSize);
        }
        else if (degree == 2){
            //C.登陆用户的degree=2,说明是大部门经理，可以查看本部门及其所有子部门创建的购销合同
            //SELECT * FROM co_contract WHERE FIND_IN_SET(create_dept,getDeptChild('100'))
            pageInfo = contractService.findByParentDept(loginUser.getDeptId(), pageNum, pageSize);
        }

        request.setAttribute("pageInfo", pageInfo);
        return "cargo/contract/contract-list";
    }

    /**
     * 2. 进入添加页面
     */
    @RequestMapping("/toAdd")

    public String toAdd(Model model) {


        //  由部门id获取本部门的经理和总经理审核人
        List<User> CheckBylist=userService.findAllUser(getLoginUser().getDeptId());
        request.setAttribute("CheckBylist",CheckBylist);
//        model.addAttribute("loginUserName",getLoginUser().getUserName());

        return "cargo/contract/contract-add";
    }

    /**
     * 3. 添加购销合同或修改购销合同
     */
    @RequestMapping("/edit")
    public String edit(Contract contract) {
        // 设置企业id、企业名称（后期再从登陆购销合同哪里获取）
        contract.setCompanyId(getLoginCompanyId());
        contract.setCompanyName(getLoginCompanyName());

        // 根据id判断是添加还是修改
        if (StringUtils.isEmpty(contract.getId())) {
            // 设置创建时间
            contract.setCreateTime(new Date());
            // 创建人
            contract.setCreateBy(getLoginUser().getId());
            // 创建人所属部门
            contract.setCreateDept(getLoginUser().getDeptId());
            // 添加
            contractService.save(contract);
        } else {
            // 修改
            Contract contractState = contractService.findById(contract.getId());
            if (contractState.getState()!=0){
                throw new RuntimeException("该状态下不可以修改！！！");
            }
            contractService.update(contract);
        }
        return "redirect:/cargo/contract/list";
    }

    /**
     * 4. 列表页面，点击编辑，进入contract-update.jsp页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id, Model model) {
        //根据购销合同id查询
        Contract contract = contractService.findById(id);
        //  由部门id获取本部门的经理和总经理审核人
        List<User> CheckBylist=userService.findAllUser(getLoginUser().getDeptId());
        request.setAttribute("CheckBylist",CheckBylist);
        //保存查询结果
        model.addAttribute("contract", contract);
        //跳转到页面
        return "cargo/contract/contract-update";
    }

    /**
     * 5. 删除
     */
    @GetMapping("/delete")
    @ResponseBody
    public Map<String, Integer> delete(String id) {
        Map<String, Integer> map = new HashMap<>();
        boolean mark = contractService.delete(id);
        if (mark){
            map.put("message", 1);
        }else {
            map.put("message", 0);
        }
        return map;
    }

    /**
     * 查看： http://localhost:8080/cargo/contract/toView.do?id=f
     * 提交： http://localhost:8080/cargo/contract/submit.do?id=f
     * 取消: http://localhost:8080/cargo/contract/cancel.do?id=f
     */
    @RequestMapping("/toView")
    public String toView(String id) {
        //根据购销合同id查询
        Contract contract = contractService.findById(id);
        //保存查询结果
        request.setAttribute("contract", contract);
        //跳转到页面
        return "cargo/contract/contract-view";
    }

    @RequestMapping("/submit")
    public String submit(String id) {
        // 提交：修改购销合同状态为1
        Contract contract = new Contract();
        contract.setId(id);   // 修改条件
        contract.setState(1); // 修改的值
        contractService.update(contract);
        return "redirect:/cargo/contract/list";
    }

    @RequestMapping("/cancel")
    public String cancel(String id) {
        // 提交：修改购销合同状态为0
        Contract contract = new Contract();
        contract.setId(id);   // 修改条件
        contract.setState(0); // 修改的值
        contractService.update(contract);
        return "redirect:/cargo/contract/list";
    }

    @RequestMapping(value = "/review", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public String review(String id)  {
        //提交查看提交状态权限
        //查询本人是否为审核人
        if (contractService.findById(id).getCheckBy().equals(getLoginUser().getUserName())) {
            //如果：状态为1 则修改购销合同状态为5 变成已审核
            if (contractService.findById(id).getState() != 1) {
//            跳回前端提示为合同状态必须为1或5才能审核 或者在前端判断
                return "合同状态必须为审核状态才能审核";//跳转带错误提示
            }
            Contract contract = new Contract();
            contract.setId(id);   // 修改条件
            contract.setState(5); // 修改的值
            contractService.update(contract);
            return "审核成功";
        }
        return "必须为审核人才能审核";//跳转带错误提示
    }
}
















